import axios from "axios"
import { ElMessage } from "element-plus"
const SUCCESS_STATUS = 'success'
const service = axios.create({ 
  baseURL: import.meta.env.VITE_BASE_API,
  timeOut: 60 * 1000,
})
// 请求拦截器
service.interceptors.request.use(
    (config)=>{
        config.headers["X-token"] = sessionStorage.getItem('X-token') || '';
        return config;
    },
    (error)=>{
        return Promise.reject(error);
    }
);
// 响应拦截器
service.interceptors.response.use(
(res)=>{
    const {config,data} = res;
    if (data.status == SUCCESS_STATUS) {
        if (config.showMessge === true) {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'success'
            })
            return data
        } else {
            return data
        }
    } else {
        switch (data.status) {
            case 400:
              error.message = "请求错误"
              break
            case 401:
              // Token 过期时
              logout()
              break
            case 403:
              error.message = "拒绝访问"
              break
            case 404:
              error.message = "请求地址出错"
              break
            case 408:
              error.message = "请求超时"
              break
            case 500:
              error.message = "服务器内部错误"
              break
            case 501:
              error.message = "服务未实现"
              break
            case 502:
              error.message = "网关错误"
              break
            case 503:
              error.message = "服务不可用"
              break
            case 504:
              error.message = "网关超时"
              break
            case 505:
              error.message = "HTTP 版本不受支持"
              break
            default:
              break
          }
        ElMessage({
            showClose: true,
            message: data.message,
            type: 'error'
        })
        return Promise.reject(data)
    }
},
(error) =>{
    ElMessage({
        showClose: true,
        message: "系统错误，请稍后刷新在重试！",
        type: 'error'
    })
    return Promise.reject(error)
}
)
export default service